package com.smartwebx.ha.web.admin.module.screen.area;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.smartwebx.ha.biz.assign.HaAreaManager;
import com.smartwebx.ha.biz.assign.HaGroupManager;
import com.smartwebx.ha.dal.assign.bean.HaArea;
import com.smartwebx.ha.dal.assign.bean.HaGroup;
import com.smartwebx.ha.dal.bean.AreaAndGroup;

public class AjaxTableArea {
	@Autowired
	private HttpServletResponse response;
	@Autowired
	private HaAreaManager haAreaManager;
	@Autowired
	private HaGroupManager haGroupManager;
	
	public void execute() throws Exception{
		response.setContentType("application/json");
		PrintWriter out=response.getWriter();
		ObjectMapper mapper=new ObjectMapper();
		
		List<HaArea> areaList=haAreaManager.findAll();
		List<HaGroup> groupList=haGroupManager.findAll();
		
		List<AreaAndGroup> areaAndGroupList=new ArrayList<AreaAndGroup>();
		
		for(HaArea haArea:areaList){
			AreaAndGroup areaAndGroup=new AreaAndGroup();
			String[] str;
			String longitude;
			String latitude;
			for(HaGroup group:groupList){
				if(haArea.getGroupId()==group.getId()){
					BeanUtils.copyProperties(haArea, areaAndGroup);
					if(haArea.getCenterPoint()!=null){
						str=haArea.getCenterPoint().split(",");
						longitude=str[0];
						latitude=str[1];
						areaAndGroup.setLongitude(Double.parseDouble(longitude));
						areaAndGroup.setLatitude(Double.parseDouble(latitude));
					}
					areaAndGroup.setGroupName(group.getName());
				}
				
			}
			areaAndGroupList.add(areaAndGroup);
		}
		
		mapper.writeValue(out, areaAndGroupList);
	}
}
